package com.zhaokuner.parentstarter.enumeration;


import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 类描述:枚举工具类
 *
 * @author 赵希坤 zhaoxikun
 * @date 2020/12/15 11:54
 */
public class SuperEnumUtil {
    /**
     * class 枚举类型
     * HashMap<Integer,SuperCodeMsg> Integer 为code
     */
    private static ConcurrentHashMap<Class<?>, HashMap<Integer, SuperCodeMsg>> enumMap = new ConcurrentHashMap<>(16);

    /**
     * 枚举code转换枚举对象
     *
     * @param code  int
     * @param clazz enum
     * @param <T>   SuperEnum
     * @return 枚举对象
     */
    public static <T extends SuperCodeMsg> T codeOf(Integer code, Class<T> clazz) {
        if (null == code) {
            return null;
        }
        HashMap<Integer, SuperCodeMsg> codeMsgMap = enumMap.get(clazz);
        if (null != codeMsgMap) {
            return (T) codeMsgMap.get(code);
        }
        codeMsgMap = new HashMap<>(8);
        try {
            SuperCodeMsg[] array = (SuperCodeMsg[]) clazz.asSubclass(Enum.class).getMethod("values").invoke(null);
            for (SuperCodeMsg superEnum : array) {
                codeMsgMap.put(superEnum.getCode(), superEnum);
            }
            enumMap.put(clazz, codeMsgMap);
        } catch (Exception e) {
            return null;
        }
        return (T) codeMsgMap.get(code);
    }

}
